﻿using Fleck;
public class Server
{
    public static List<IWebSocketConnection> clients = new List<IWebSocketConnection>();
    public static bool[] seats = new bool[2] { false, false };
    public static void Main(string[] args)
    {
        var server = new WebSocketServer("ws://10.0.4.9:10000");
        server.Start(client =>
           {
               client.OnOpen = () =>
               {
                   clients.Add(client);
               };
               client.OnClose = () =>
               {
                   clients.Remove(client);
                   seats[0] = seats[1] = false;
               };
               client.OnMessage = message =>
               {
                   DoMessage(client, message);
                   Console.WriteLine($"收到一条消息，来自：{client.ConnectionInfo.ClientPort}, {message}");
               };
           });

        Console.WriteLine("服务器已经启动！");
        Console.ReadLine();
    }
    public static void DoMessage(IWebSocketConnection socket, string message)
    {
        string[] args = message.Split('|');
        if (args[0] == "ready")
        {
            Random r = new Random();
            int v = 0;
            if (seats[v])
                v = 1 - v;
            seats[v] = true;
            socket.Send("ready|" + v);
            if (seats[0] && seats[1])
            {
                clients[0].Send("start|");
                clients[1].Send("start|");
            }
        }
        else
        {
            Random r = new Random();
            int v = r.Next(0, 6);
            foreach (var c in clients)
            {
                if (args[0] == "init")
                {
                    c.Send("init|" + v);
                }
                else
                    c.Send(message);
            }
        }

    }
}